<?php
declare (strict_types = 1);

namespace app\home\middleware;

use app\common\model\User\User;
use think\facade\View;
use app\common\model\Config as ConfigModel;

class LoginAuth
{
    // 调用跳转扩展
    use \liliuwei\think\Jump;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取cookie
        $LoginUser = !empty(cookie('LoginUser')) ? json_decode(cookie('LoginUser'),true) : [];

        if(empty($LoginUser))
        {
            $this->error('请先登录',(String)url('/home/index/login'));
        }

        $userid = isset($LoginUser['id']) ? $LoginUser['id'] : 0;

        // 查询该用户是否存在数据库
        $user = User::find($userid);

        if(!$user)
        {
            cookie('LoginUser',null);
            $this->error('非法登录,请重新登录',(String)url('/home/index/login'));
        }

        $data = [
            'id' => $user['id'],
            'email' => $user['email'],
            'nickname' => $user['nickname'],
            'avatar' => $user['avatar'],
            'sex' => $user['sex'],
            'province' => $user['province'],
            'city' => $user['city'],
            'district' => $user['district'],
            'content' => $user['content'],
            'point' => $user['point'],
            'vip' => $user['vip'],
            'auth' => $user['auth'],
            'cover' => $user['cover'],
            'region_text'=> $user['region_text'],
            'createtime' => $user['createtime'],
            'sign' => $user['sign']
        ];

        $ConfigList = ConfigModel::select();

        $Config = [];

        foreach ($ConfigList as $key => $value) {
           $Config[$value['key']] = $value['value'];
        }

        // 赋值给所有使用该中间件的视图
        View::assign([
            'LoginUser' => $data,
            'Config'=>$Config
        ]);
        // halt($Config);
        // 赋值给所有使用该中间件的控制器
        $request->LoginUser = $data;

        return $next($request);
    }
}
